import {TragedyCalculator, ComedyCalculator} from "./PerformanceCalculator.js";


// 优化计算阶段，更好的满足其他类型戏剧的增加
function createStatement(invoice, plays) {

  let result = {};
  result.customer = invoice.customer;
  result.performances = invoice.performances.map(enrichPerformance);
  result.totalAmount = totalAmount(result);
  result.totalVolumeCredits = totalVolumeCredits(result);
  return result;

  // 内联变量
  function playFor(performance) {
    return plays[performance.playID]
  }

  function createPerformanceCalculator(performance, play) {
    switch (play.type) {
      case "tragedy":
        return new TragedyCalculator(performance, play);
      case "comedy":
        return new ComedyCalculator(performance, play);
      default:
        throw new Error(`UnSupport Type: ${play.type}`);
    }
  }

  // 填充performance对象
  function enrichPerformance(performance) {
    let calculator = createPerformanceCalculator(performance, playFor(performance));
    let result =  Object.assign({}, performance);
    result.play = calculator.play;
    result.amount = calculator.amount;
    result.volumeCredits = calculator.volumeCredits;
    return result;
  }

  // 代码搬移，计算总金额
  function totalAmount(statementData) {
    return statementData.performances.reduce((prev, curr) => prev + curr.amount, 0);
  }

  // 代码搬移，计算总积分
  function totalVolumeCredits(statementData) {
    return statementData.performances.reduce((prev, curr) => prev + curr.volumeCredits, 0);
  }

}

export { createStatement };